/**
 * @description 接收表单的值
 * @author 大肘子
 */

//规范化接收的数据

function getAnswerInfo(reqBody:any){
    const answerList: { componentId: string; value: any }[] = []
    Object.keys(reqBody).forEach((key)=>{
        if(key == 'questionId') return
        answerList.push({
            componentId:key,
            value:reqBody[key] as string
        })
    })
    return {
        questionId:reqBody.questionId || '',
        answerList:answerList
    }
}


import type { NextApiRequest, NextApiResponse } from 'next'
import { postAnswer } from '@/services/Answer';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
   if(req.method == 'POST'){
    const answerInfo = getAnswerInfo(req.body)
    console.log("问卷数据",answerInfo)
    try{
         // 提交数据到mock 通过自己建立的service进行与后端的数据链接
        const data = await postAnswer(answerInfo)
        
        if(data.errno == 0){
            res.redirect('/success')
        }else{
            res.redirect('/fail')
        }
       
    }catch{
        res.redirect('/fail')
    }
   }else{
    res.status(200).json({ error:-1, msg:'提交方法错误'})
   }
 
}
